<template>
  <div class="login-container">
    <div class="login-background">
      <div class="floating-shapes">
        <div class="shape shape-1"></div>
        <div class="shape shape-2"></div>
        <div class="shape shape-3"></div>
        <div class="shape shape-4"></div>
      </div>
    </div>

    <div class="login-content">
      <div class="login-card">
        <div class="login-header">
          <div class="logo-container">
            <div class="logo-icon">
              <i class="el-icon-setting"></i>
            </div>
            <h1 class="system-title">后台管理系统</h1>
            <p class="system-subtitle">Admin Management System</p>
          </div>
        </div>

        <el-form
          :model="loginForm"
          :rules="loginRules"
          ref="loginFormRef"
          @keyup.enter="handleLogin"
          class="login-form"
          size="large">
          <el-form-item prop="username">
            <el-input
              v-model="loginForm.username"
              placeholder="请输入用户名"
              :prefix-icon="User"
              clearable
              @focus="handleInputFocus"
              @blur="handleInputBlur" />
          </el-form-item>

          <el-form-item prop="password">
            <el-input
              v-model="loginForm.password"
              type="password"
              placeholder="请输入密码"
              :prefix-icon="Lock"
              show-password
              clearable
              @focus="handleInputFocus"
              @blur="handleInputBlur" />
          </el-form-item>

          <el-form-item>
            <div class="login-options">
              <el-checkbox v-model="loginForm.rememberMe" class="remember-checkbox"> 记住我 </el-checkbox>
              <el-link type="primary" @click="handleForgotPassword" class="forgot-link"> 忘记密码？ </el-link>
            </div>
          </el-form-item>

          <el-form-item>
            <el-button
              type="primary"
              class="login-button"
              @click="handleLogin"
              :loading="loading"
              :disabled="!isFormValid">
              <span v-if="!loading">登录</span>
              <span v-else>登录中...</span>
            </el-button>
          </el-form-item>
        </el-form>

        <div class="login-footer">
          <p class="footer-text">
            还没有账号？
            <el-link type="primary" @click="handleRegister" class="register-link"> 立即注册 </el-link>
          </p>
        </div>

        <!-- 错误提示 -->
        <div v-if="errorMessage" class="error-message">
          <el-alert :title="errorMessage" type="error" show-icon :closable="false" />
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from "vue";
import { useRouter } from "vue-router";
import { ElMessage, ElMessageBox } from "element-plus";
import { User, Lock } from "@element-plus/icons-vue";
import { http } from "@/api";

const router = useRouter();
const loginFormRef = ref(null);
const loading = ref(false);
const errorMessage = ref("");

// 登录表单数据
const loginForm = reactive({
  username: "",
  password: "",
  rememberMe: false,
});

// 表单验证规则
const loginRules = {
  username: [
    { required: true, message: "请输入用户名", trigger: "blur" },
    { min: 3, max: 20, message: "用户名长度在 3 到 20 个字符", trigger: "blur" },
    { pattern: /^[a-zA-Z0-9_]+$/, message: "用户名只能包含字母、数字和下划线", trigger: "blur" },
  ],
  password: [
    { required: true, message: "请输入密码", trigger: "blur" },
    { min: 6, message: "密码长度不能少于 6 个字符", trigger: "blur" },
  ],
};

// 计算表单是否有效
const isFormValid = computed(() => {
  return loginForm.username.trim() && loginForm.password.trim();
});

// 页面加载时检查是否有保存的登录信息
onMounted(() => {
  const savedUsername = localStorage.getItem("savedUsername");
  const savedRememberMe = localStorage.getItem("rememberMe");

  if (savedUsername && savedRememberMe === "true") {
    loginForm.username = savedUsername;
    loginForm.rememberMe = true;
  }
});

// 处理输入框焦点
const handleInputFocus = () => {
  errorMessage.value = "";
};

// 处理输入框失焦
const handleInputBlur = () => {
  // 可以在这里添加额外的验证逻辑
};

// 处理登录
const handleLogin = async () => {
  try {
    // 清除之前的错误信息
    errorMessage.value = "";

    // 表单验证
    await loginFormRef.value.validate();

    loading.value = true;

    // 调用登录API
    const response = await http.post("/api/auth/login", {
      username: loginForm.username.trim(),
      password: loginForm.password,
    });

    if (response.code === 200) {
      // 保存token
      localStorage.setItem("token", response.data.token);

      // 保存用户信息
      localStorage.setItem("userInfo", JSON.stringify(response.data.userInfo));

      // 记住用户名
      if (loginForm.rememberMe) {
        localStorage.setItem("savedUsername", loginForm.username);
        localStorage.setItem("rememberMe", "true");
      } else {
        localStorage.removeItem("savedUsername");
        localStorage.removeItem("rememberMe");
      }

      ElMessage.success({
        message: "登录成功，正在跳转...",
        duration: 1500,
        onClose: () => {
          // 检查是否有重定向地址
          const redirect = router.currentRoute.value.query.redirect;
          if (redirect) {
            // 跳转到原来的页面
            router.push(redirect);
          } else {
            // 跳转到首页
            router.push("/dashboard");
          }
        },
      });
    } else {
      errorMessage.value = response.message || "登录失败，请检查用户名和密码";
    }
  } catch (error) {
    console.error("登录失败:", error);

    if (error.response?.status === 401) {
      errorMessage.value = "用户名或密码错误";
    } else if (error.response?.status === 400) {
      errorMessage.value = "请求参数错误，请检查输入";
    } else if (error.response?.status === 500) {
      errorMessage.value = "服务器内部错误，请稍后重试";
    } else if (!error.response) {
      errorMessage.value = "网络连接失败，请检查网络设置";
    } else {
      errorMessage.value = "登录失败，请稍后重试";
    }
  } finally {
    loading.value = false;
  }
};

// 处理忘记密码
const handleForgotPassword = () => {
  ElMessageBox.alert("请联系系统管理员重置密码，或发送邮件至 admin@example.com", "忘记密码", {
    confirmButtonText: "确定",
    type: "info",
    center: true,
  });
};

// 处理注册
const handleRegister = () => {
  ElMessageBox.alert("请联系系统管理员创建账号，或发送邮件至 admin@example.com", "注册账号", {
    confirmButtonText: "确定",
    type: "info",
    center: true,
  });
};
</script>

<style scoped>
.login-container {
  height: 100vh;
  width: 100vw;
  display: flex;
  justify-content: center;
  align-items: center;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  position: relative;
  overflow: hidden;
}

.login-background {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  z-index: 0;
}

.floating-shapes {
  position: relative;
  width: 100%;
  height: 100%;
}

.shape {
  position: absolute;
  border-radius: 50%;
  background: rgba(255, 255, 255, 0.1);
  animation: float 6s ease-in-out infinite;
}

.shape-1 {
  width: 80px;
  height: 80px;
  top: 20%;
  left: 10%;
  animation-delay: 0s;
}

.shape-2 {
  width: 120px;
  height: 120px;
  top: 60%;
  right: 10%;
  animation-delay: 2s;
}

.shape-3 {
  width: 60px;
  height: 60px;
  top: 40%;
  left: 20%;
  animation-delay: 4s;
}

.shape-4 {
  width: 100px;
  height: 100px;
  top: 80%;
  left: 60%;
  animation-delay: 1s;
}

@keyframes float {
  0%,
  100% {
    transform: translateY(0px) rotate(0deg);
  }
  50% {
    transform: translateY(-20px) rotate(180deg);
  }
}

.login-content {
  position: relative;
  z-index: 1;
}

.login-card {
  width: 420px;
  background: rgba(255, 255, 255, 0.95);
  border-radius: 16px;
  box-shadow: 0 20px 40px rgba(0, 0, 0, 0.1);
  backdrop-filter: blur(10px);
  border: 1px solid rgba(255, 255, 255, 0.2);
  padding: 40px;
}

.login-header {
  text-align: center;
  margin-bottom: 40px;
}

.logo-container {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.logo-icon {
  width: 80px;
  height: 80px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-bottom: 20px;
  box-shadow: 0 8px 24px rgba(102, 126, 234, 0.3);
}

.logo-icon i {
  font-size: 36px;
  color: white;
}

.system-title {
  margin: 0 0 8px 0;
  color: #333;
  font-size: 28px;
  font-weight: 600;
}

.system-subtitle {
  margin: 0;
  color: #666;
  font-size: 14px;
  font-weight: 400;
}

.login-form {
  margin-bottom: 20px;
}

.login-form .el-form-item {
  margin-bottom: 24px;
}

.login-options {
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: 100%;
}

.remember-checkbox {
  color: #666;
}

.forgot-link {
  font-size: 14px;
}

.login-button {
  width: 100%;
  height: 48px;
  font-size: 16px;
  font-weight: 500;
  border-radius: 8px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border: none;
  transition: all 0.3s ease;
}

.login-button:hover {
  background: linear-gradient(135deg, #5a6fd8 0%, #6a4190 100%);
  transform: translateY(-2px);
  box-shadow: 0 8px 24px rgba(102, 126, 234, 0.3);
}

.login-button:disabled {
  background: #ccc;
  transform: none;
  box-shadow: none;
}

.login-footer {
  text-align: center;
  padding-top: 20px;
  border-top: 1px solid #f0f0f0;
}

.footer-text {
  margin: 0;
  color: #666;
  font-size: 14px;
}

.register-link {
  font-size: 14px;
}

.error-message {
  margin-top: 20px;
}

/* 输入框样式 */
:deep(.el-input__wrapper) {
  border-radius: 8px;
  transition: all 0.3s ease;
}

:deep(.el-input__wrapper:hover) {
  box-shadow: 0 0 0 1px #667eea;
}

:deep(.el-input__wrapper.is-focus) {
  box-shadow: 0 0 0 2px rgba(102, 126, 234, 0.2);
}

/* 响应式设计 */
@media (max-width: 480px) {
  .login-card {
    width: 90%;
    margin: 0 20px;
    padding: 30px 20px;
  }

  .system-title {
    font-size: 24px;
  }

  .logo-icon {
    width: 60px;
    height: 60px;
  }

  .logo-icon i {
    font-size: 28px;
  }
}
</style>
